package it.storm.solution;

import java.util.Arrays;

/**
 * 566. 重塑矩阵
 * https://leetcode-cn.com/problems/reshape-the-matrix/
 */
public class Solutions_566 {
    public static void main(String[] args) {
//        int[][] nums = {{1, 2}, {3, 4}};
//        int r = 1, c = 4;  // output: {{1, 2, 3, 4}}

        int[][] nums = {{1, 2}, {3, 4}};
        int r = 2, c = 4;  // output: {{1, 2}, {3, 4}}

        int[][] result = matrixReshape(nums, r, c);
        System.out.println(Arrays.deepToString(result));
    }

    public static int[][] matrixReshape(int[][] nums, int r, int c) {
        if (nums == null) {
            return new int[0][0];
        }
        // 个数是否符合
        int row = nums.length, col = nums[0].length;
        if (r * c != row * col) {
            // 无法转换
            return nums;
        }
        int[][] res = new int[r][c];
        int idx = 0;

        // nums 中元素依次添加到 res 矩阵中
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                int curRow = idx / c;
                int curCol = idx % c;
                res[curRow][curCol] = nums[i][j];
                idx ++;
            }
        }
        return res;
    }
}
